<?php
class SiteModule
{
	public function index()
	{
		global $_FANWE;

		$cache_args = array(
			$_FANWE['cookie']['city_py'],
		);

		$_FANWE['nav_title'] = lang('common','site_index');

		$cache_file = getTplCache('page/site_index',$cache_args);

		if(!@include($cache_file))
			include template('page/site_index');

		display($cache_file);
	}

	public function show()
	{
		global $_FANWE;

		$id = intval($_FANWE['request']['id']);
		if($id == 0)
			fHeader('location:./');

		if($_FANWE['setting']['site_show_type'] == 0)
		{
			SiteModule::go();
			return;
		}

		//用于网站评论的发表频率限制
		$key = $_FANWE['uid'].'_check_site_message_'.$id;
		if(empty($_FANWE['cookie'][$key]))
			fSetCookie($key, authcode($_FANWE['client_ip']."\t0", 'ENCODE'),604800, 1, true);

		S("RankStatistic")->site($id,'SITE_CLICK');

		$cache_args = array(
			$id,
		);

		$cache_file = getTplCache('page/site_show',$cache_args);

		if(!@include($cache_file))
		{
			$site = DB::fetchFirst('SELECT * FROM '.DB::table('site').' WHERE id = '.$id.' AND status = 1');
			if(!$site)
				fHeader('location:./');

			$_FANWE['nav_title'] = $site['name'];

			$site['go_url'] = U('site/go',array('id'=>$site['id']));
			$site['content'] = stripslashes($site['content']);
			include template('page/site_show');
		}

		display($cache_file);
	}

	public function go()
	{
		global $_FANWE;

		$id = intval($_FANWE['request']['id']);
		if($id == 0)
			fHeader('location:./');

		$site = $_FANWE['cache']['site']['all']['s_'.$id];

		if(isset($site['site_url']) && !empty($site['site_url']))
		{
			$_FANWE['nav_title'] = $site['name'];
			S("RankStatistic")->site($id,'SITE_CLICK');

			if(!empty($site['invite_url']))
				fHeader('location: '.$site['invite_url']);
			else
				fHeader('location: '.$site['site_url']);
		}
		else
			fHeader('location:./');
	}

	public function submit()
	{
		global $_FANWE;

		$cache_args = array(
			$_FANWE['cookie']['city_py'],
		);

		$_FANWE['nav_title'] = lang('common','site_submit');

		$cache_file = getTplCache('page/site_submit',$cache_args);

		//用于网站提交的发表频率限制
		$key = $_FANWE['uid'].'_check_site_submit';
		if(empty($_FANWE['cookie'][$key]))
			fSetCookie($key, authcode($_FANWE['client_ip']."\t0", 'ENCODE'),604800, 1, true);

		if(!@include($cache_file))
		{
			$rule_type = array();
			$query = DB::query('SELECT * FROM '.DB::table('collect_rule_type').' WHERE status = 1');
			while($data = DB::fetch($query))
			{
				$rule_type[] = $data;
			}

			include template('page/site_submit');
		}

		display($cache_file);
	}

	public function save()
	{
		global $_FANWE;
		$_FANWE['nav_title'] = lang('common','site_submit');
		$data['user_name'] = $_FANWE['request']['user_name'];
		$data['user_email'] = $_FANWE['request']['user_email'];
		$data['user_pwd'] = $_FANWE['request']['user_pwd'];
		$data['title'] = $_FANWE['request']['title'];
		$data['content'] = $_FANWE['request']['content'];
		$data['qq_msn'] = $_FANWE['request']['qq_msn'];
		$data['tel'] = $_FANWE['request']['tel'];
		$data['score'] = intval($_FANWE['request']['rule_type']);
		$data['api'] = $_FANWE['request']['api'];
		$data['rec_id'] = intval($_FANWE['request']['rec_id']);
		$data['rec_module'] = 'Site';
		$data['status'] = 0;
		$data['create_time'] = TIME_UTC;
		$data['update_time'] = TIME_UTC;

		$validate  = array(
			array('title','required',lang('site','web_name_empty')),
			array('content','required',lang('site','web_url_empty')),
			array('content','url',lang('site','web_url_error')),
			array('user_name','required',lang('site','user_name_empty')),
			array('user_name','range_length',lang('site','user_name_error'),3,10),
			array('user_email','required',lang('site','user_email_empty')),
			array('user_email','email',lang('site','user_email_error')),
			array('user_pwd','required',lang('site','user_pwd_empty')),
			array('qq_msn','required',lang('site','qq_msn_empty')),
			array('qq_msn','qq_msn',lang('site','qq_msn_error')),
		);

		if(!S('Validate')->validation($validate,$data))
			$error = S('Validate')->getError();

		if($error != '')
		{
			if(S('Site')->getUrlExists($data['content']))
				$error = lang('site','web_url_exists');
		}

		if($error != '')
		{
			if(S('User')->getUserNameExists($data['user_name']))
				$error = lang('site','web_name_exists');
		}

		if($error != '')
		{
			if(S('User')->getEmailExists($data['user_email']))
				$error = lang('site','user_email_exists');
		}

		if($error == '')
		{
			if(checkIpOperation("site_submit",$_FANWE['setting']["message_inteval"]))
			{
				if(DB::insert('message',$data))
				{
					showSuccess(lang('site','site_tooltip'),
								lang('site','site_success'),
								U('index/index'));
				}
				else
					$error = lang('site','site_error');
			}
			else
				$error = lang('site','site_frequent');
		}

		$rule_type = array();
		$query = DB::query('SELECT * FROM '.DB::table('collect_rule_type').' WHERE status = 1');
		while($type = DB::fetch($query))
		{
			$rule_type[] = $type;
		}

		$site_data = &$data;
		include template('page/site_submit');
		display();
	}
	
	public function center()
	{
		global $_FANWE;
		$_FANWE['nav_title'] = lang('common','site_center');
		
		$cache_args = array(
			
		);
		
		$cache_file = getTplCache('page/site_center',$cache_args);
		if(!@include($cache_file))
			include template('page/site_center');
		
		display($cache_file);
	}
	
	public function top()
	{
		$cache_file = getTplCache('site/top');
		if(!@include($cache_file))
			include template('site/top');
		display($cache_file);
	}
	
	public function menu()
	{
		global $_FANWE;
		$cache_file = getTplCache('site/menu');
		if(!@include($cache_file))
			include template('site/menu');
		display($cache_file);
	}
	
	public function password()
	{
		global $_FANWE;
		include template('site/password');
		display();
	}
	
	public function repwd()
	{
		global $_FANWE;
		
		$user = S('User')->getUserById($_FANWE['user']['id']);
		
		if(md5($_FANWE['request']['yuan_pwd']) == $user['user_pwd'])
		{
			$code = $_FANWE['setting']['integrate_code'];
			if (empty($code))
				$code = 'fanwe';
			
			if($code != 'fanwe')
			{
				$users = &init_users();
				$uc['email'] = '';
				$uc['username'] = $user['user_name']; 
				$uc['password'] = $_FANWE['request']['user_pwd'];
				$users->edit_user($uc);
			}
			
			$user['user_pwd'] = md5($_FANWE['request']['user_pwd']);
			$user['update_time'] = TIME_UTC;
			$success = '修改密码成功';
			
			DB::update('user',array('user_pwd'=>$user['user_pwd']),'id = '.$_FANWE['user']['id']);
			
			S('User')->setSession($user);
		}
		else
		{
			$error = '原密码不正确，请重新输入';
		}
		
		include template('site/password');
		display();
	}
	
	public function siteInfo()
	{
		global $_FANWE;
		$site = S('Site')->getSiteByUserID($_FANWE['uid']);
		if($site)
			SiteModule::showSite($site);
	}
	
	public function siteUpdate()
	{
		global $_FANWE;

		$id = intval($_FANWE['request']['id']);
		$user_site = S('site')->getSiteByUserID($_FANWE['uid']);
		
		if($user_site['id'] == $id)
		{
			$site['content'] = $_FANWE['request']['content'];
			$user_site['content'] = $site['content'];
			
			include import('class/upload');
			$upload = new Upload();
			$upload->init($_FILES['img_file'],'site');
			if($upload->save())
			{
				if($upload->file['ext'] == 'swf')
					unlink($upload->file['local_target']);
				else
				{
					$site['site_img'] = '/'.$upload->file['target'];
					$user_site['site_img'] = '/'.$upload->file['target'];
				}
			}
			
			S('Site')->updateSiteByUserID($id,$_FANWE['uid'],$site);
		}
		else
			exit;
		
		
		SiteModule::showSite($user_site);
	}
	
	private function showSite($site)
	{
		$site['content'] = stripslashes($site['content']);
		include FANWE_ROOT.'./public/fckeditor/fckeditor.php';
		$fckeditor = new FCKeditor('content');
		$fckeditor->Width = "100%";
		$fckeditor->Height = "300";
		$fckeditor->Value = $site['content'] ;
		$fck = $fckeditor->CreateHtml();
		
		include template('site/siteinfo');
		display();
	}
	
	public function recharge()
	{
		global $_FANWE;
		$payment_list = S('Payment')->getPaymentList();
		$incharge_id = intval($_FANWE['request']['id']);
		$incharge = array('payment'=>0,'money'=>0);
		if($incharge)
		{
			$incharge = DB::fetchFirst('SELECT id,payment,money FROM '. DB::table('user_incharge').' WHERE is_paid = 0 AND user_id = '.$_FANWE['uid'].' AND id = '.$incharge_id);
			$incharge['money'] = floatval($incharge['money']);
		}
		
		$incharge['score'] = $_FANWE['setting']['money_score_ratio'] * $incharge['money'];
		
		include template('site/recharge');
		display();
	}
	
	public function rechargeHandle()
	{
		global $_FANWE;
		$payment = intval($_FANWE['request']['payment']);
		$amount = intval($_FANWE['request']['amount']);
		$incharge_id = intval($_FANWE['request']['id']);
		
		if($payment < 1)
			$error = '请选择支付方式';
		
		if(empty($error) && $amount < 1)
			$error = '请输入要充值的金额';
		
		if(empty($error))
		{
			if($incharge_id == 0)
			{
				$data = array ();
				$data ['user_id'] = $_FANWE['uid'];
				$data ['money'] = $amount;
				$data ['is_paid'] = 0;
				$data ['payment'] = $payment;
				$data ['create_time'] = TIME_UTC;
				$data ['update_time'] = TIME_UTC;
			
				$payment_info = DB::fetchFirst('SELECT fee_type,fee FROM '. DB::table('payment').' WHERE id = '.$payment);
			
				if ($payment_info ['fee_type'] == 0)
					$data['payment_fee'] = $payment_info['fee'];
				else
					$data['payment_fee'] = $amount * $payment_info['fee'] / 100;
			
				$data ['payment_money'] = $data['money'] + $data['payment_fee'];
				
				$do_count = 0;
				do
				{
					$data['sn'] = toDate(TIME_UTC,'ymdHis').rand(0,9999);
					if ($incharge_id = DB::insert('user_incharge',$data,true,false,true))
						break;
					else
					{
						if (DB::errno() != 1062)
						{
							$error = DB::error();
							break;
						}
					}
					$do_count = $do_count + 1;
				}while($do_count < 10);
			
				if($do_count >= 10)
					$error = '数据写入错误';
				
				if(intval($incharge_id) == 0)
					$error = '数据写入错误';
			}
			else
			{
				$data = DB::fetchFirst('SELECT * FROM '. DB::table('user_incharge').' WHERE is_paid = 0 AND user_id = '.$_FANWE['uid'].' AND id = '.$incharge_id);
				if($data)
				{
					$data ['money'] = $amount;
					$data ['payment'] = $payment;
					$data ['update_time'] = TIME_UTC;
				
					$payment_info = DB::fetchFirst('SELECT fee_type,fee FROM '. DB::table('payment').' WHERE id = '.$payment);
				
					if ($payment_info ['fee_type'] == 0)
						$data['payment_fee'] = $payment_info['fee'];
					else
						$data['payment_fee'] = $amount * $payment_info['fee'] / 100;
				
					$data ['payment_money'] = $data['money'] + $data['payment_fee'];
					
					DB::update('user_incharge',$data,'id = '.$incharge_id);
				}
				else
					$error = '该记录不存在';
			}
			
			if(empty($error))
				$payment_str = S('Payment')->getPayment($incharge_id);
		}
		
		if(empty($error))
			include template('site/pay');
		else
			include template('site/recharge');
		
		display();
	}
	
	public function money()
	{
		global $_FANWE;
		
		$args = array();
		$where = " user_id = ".$_FANWE['user']['id'];
		$status = intval($_FANWE['request']['status']);
		if($status > 0)
		{
			$where.=" AND is_paid = ".($status - 1);
			$args['status'] = $status;
		}
		else
		{
			$status = 0;
		}
		
		$count = DB::resultFirst('SELECT COUNT(id) FROM '.DB::table('user_incharge').' WHERE '.$where);
		$pager = buildPage('site/money',$args,$count,$_FANWE['page'],$_FANWE['setting']['page_listrows']);
	
		$sql = 'SELECT * FROM '.DB::table('user_incharge').' WHERE '.$where.' ORDER BY id DESC LIMIT '.$pager['limit'];
		
		$res = DB::query($sql);
		$list = array();
		while($data = DB::fetch($res))
		{
			$data['create_time'] = toDate($data['create_time']);
			$data['update_time'] = toDate($data['update_time']);
			$data['money'] = "¥".floatval($data['money']);
			$data['payment_fee'] = "¥".floatval($data['payment_fee']);
			$data['payment_money'] = "¥".floatval($data['payment_money']);
			$list[] = $data;
		}
		
    	include template('site/moneylog');
		display();
    }
	
	public function score()
	{
		global $_FANWE;
		
		$args = array();
		
		$count = DB::resultFirst('SELECT COUNT(id) FROM '.DB::table('user_score_log').' WHERE user_id = '.$_FANWE['uid']);
				
		$pager = buildPage('site/score',$args,$count,$_FANWE['page'],$_FANWE['setting']['page_listrows']);
		$query = DB::query('SELECT * FROM '.DB::table('user_score_log').' WHERE user_id = '.$_FANWE['uid'].' ORDER BY id DESC LIMIT '.$pager['limit']);
		
		$list = array();
					
		while($log = DB::fetch($query))
		{
			$log['create_time'] = toDate($log['create_time']);
			$list[] = $log;
		}
		
		include template('site/scorelist');
		display();
    }
	
	public function auction()
	{
		global $_FANWE;
		
		$time = TIME_UTC;
		
		$args = array();
	
		$order = $_FANWE['request']['order'];
		
		$orders = array(
			'begin_time' => 'a.validity_begin_time DESC',
			'end_time' => 'a.validity_end_time ASC',
			'click' => 's.num DESC',
			'price' => 's.outlay_money DESC'
		);
		
		$sort = $orders['begin_time'];
		
		$type = $_FANWE['request']['type'];
		
		$types = array('now','wait','expired');
		
		if(empty($type) || !in_array($type,$types))
			$type = '';
		else
			$args['type'] = $type;
		
		if(empty($order) || !array_key_exists($order,$orders))
			$order = '';
		else
		{
			$args['order'] = $order;
			$sort = $orders[$order];
		}
			
		$where = ' AND a.user_id = '.$_FANWE['uid'];
		
		switch($type)
		{
			case 'now':
				$where .= ' AND a.validity_begin_time <= '.$time.' AND (a.validity_end_time = 0 OR a.validity_end_time > '.$time.')';
			break;
		
			case 'wait':
				$where .= ' AND a.validity_begin_time > 0 AND a.validity_begin_time > '.$time;
			break;
		
			case 'expired':
				$where .= ' AND a.validity_end_time > 0 AND a.validity_end_time < '.$time;
			break;
		}
		
		$count = DB::resultFirst('SELECT COUNT(a.id) FROM '.DB::table('auction').' as a
				WHERE a.auction_status = 1 '.$where);
				
		$pager = buildPage('site/auction',$args,$count,$_FANWE['page'],$_FANWE['setting']['page_listrows']);
		$query = DB::query('SELECT a.id,a.name,a.auction_type,a.billing_type,a.validity_begin_time,
                        a.validity_end_time,s.num,s.outlay_money,s.freeze_money FROM '.DB::table('auction').' AS a 
							LEFT JOIN '.DB::table('auction_statistic').' AS s ON s.auction_id = a.id  
							WHERE a.auction_status = 1 '.$where.' ORDER BY '.$sort.' LIMIT '.$pager['limit']);
		
		$list = array();
					
		while($data = DB::fetch($query))
		{
			$data['validity_begin_time_format'] = toDate($data['validity_begin_time']);
			$data['validity_end_time_format'] = toDate($data['validity_end_time']);
			$data['click'] = intval($data['num']);
			$data['outlay_money_format'] = '¥'.floatval($data['outlay_money']);
			$data['freeze_money_format'] = '¥'.floatval($data['freeze_money']);
			$data['url'] = U('auction/show',array('id'=>$data['id']));
			$list[] = $data;
		}
		
		include template('site/auctionlist');
		display();
    }
	
	public function statistic()
	{
		global $_FANWE;
		
		$aid = intval($_FANWE['request']['aid']);
		if($aid == 0)
			exit;
		
		$aid = intval(DB::resultFirst('SELECT id FROM '.DB::table('auction').' WHERE user_id = '.$_FANWE['uid'].' AND id = '.$aid));
		
		if($aid == 0)
			exit;
		
		$type = $_FANWE['request']['type'];
		$types = array('charts','list');
		if(empty($type) || !in_array($type,$types))
			$type = 'charts';
		
		if($type == 'list')
		{
			$min_time = intval(DB::resultFirst('SELECT MIN(click_time) FROM '.DB::table('auction_click_'.$aid)));
			$time = TIME_UTC;
			$min_year = toDate($min_time,'Y');
			$max_year = toDate($time,'Y');
			$current_year = $max_year;
			$current_month = toDate($time,'m');
			$current_date = toDate($time,'d');
		
			$years = array();
			for($max_year;$max_year >= $min_year;$max_year--)
			{
				$years[] = $max_year;
			}
		
			$months = array();
			for($min_month = 1;$min_month <= 12;$min_month++)
			{
				$months[] = $min_month > 9 ? $min_month : '0'.$min_month;
			}
		
			$dates = array();
			for($min_date = 1;$min_date <= 31;$min_date++)
			{
				$dates[] = $min_date > 9 ? $min_date : '0'.$min_date;
			}
		
			$tyear = intval($_FANWE['request']['tyear']);
			$tmonth = intval($_FANWE['request']['tmonth']);
			$tdate = intval($_FANWE['request']['tdate']);
		
			if(in_array($tyear,$years))
				$current_year = $tyear;
		
			if($tmonth < 0)
				$current_month = 0;
			elseif($tmonth > 12)
				$current_month = 12;
			elseif($tmonth > 0)
				$current_month = $tmonth;
		
			if($tdate < 0 || $current_month == 0)
				$current_date = 0;
			elseif($current_month > 0 && $tdate > 0)
			{
				if($current_month == 12)
					$max_date = (str2Time(($current_year + 1).'-01-01') - str2Time($current_year.'-'.$current_month.'-01')) / (24 * 3600);
				else
					$max_date = (str2Time($current_year.'-'.($current_month + 1).'-01') - str2Time($current_year.'-'.$current_month.'-01')) / (24 * 3600);
		
				if($tdate > $max_date)
					$tdate = $max_date;
		
				$current_date = $tdate;
			}
		
			if($current_date > 0)
			{
				$begin_time = mktime(0,0,0,$current_month,$current_date,$current_year) - date('Z');
				$end_time = mktime(0,0,0,$current_month,intval($current_date) + 1,$current_year) - date('Z');
			}
			elseif($current_month > 0)
			{
				$begin_time = mktime(0,0,0,$current_month,1,$current_year) - date('Z');
				$end_time = mktime(0,0,0,$current_month + 1,1,$current_year) - date('Z');
			}
			else
			{
				$begin_time = mktime(0,0,0,1,1,$current_year) - date('Z');
				$end_time = mktime(0,0,0,1,1,$current_year + 1) - date('Z');
			}
			
			$count = DB::resultFirst('SELECT count(*) FROM '.DB::table('auction_click_'.$aid)." WHERE click_time > $begin_time AND click_time <= $end_time");
			
			$pager = buildPage('site/statistic',array(),$count,$_FANWE['page'],20,"site.php?action=statistic&type=list&aid=$aid&tyear=$tyear&tmonth=$tmonth&tdate=$tdate&page=");
			$query = DB::query('SELECT * FROM '.DB::table('auction_click_'.$aid)." WHERE click_time > $begin_time AND click_time <= $end_time LIMIT ".$pager['limit']);
		
			$list = array();
			while($data = DB::fetch($query))
			{
				$data['click_time'] = toDate($data['click_time']);
				$list[] = $data;
			}
			
			include template('site/statisticlist');
		}
		else
		{
			$time_type = trim($_FANWE['request']['time_type']);
			$times = SiteModule::getTimeTypes($time_type);
			$time_type = $times['type'];
			$time_vals = $times['vals'];
			include template('site/charts');
		}
		
		display();
    }
	
	public function getStatistic()
	{
		@header('Content-Type: text/xml; charset=utf-8');
		
		global $_FANWE;
		
		$aid = intval($_FANWE['request']['aid']);
		
		if($aid == 0)
			exit;
		
		$aid = intval(DB::resultFirst('SELECT id FROM '.DB::table('auction').' WHERE user_id = '.$_FANWE['uid'].' AND id = '.$aid));
		
		if($aid == 0)
			exit;
		
		$time_type = trim($_FANWE['request']['time_type']);
		$times = SiteModule::getTimeTypes($time_type);
		$time_type = $times['type'];
		$time_vals = $times['vals'];
		
		$ylabel = "点击量";
		$old_h = $time_vals[$time_type]['time'];
		$title = $time_vals[$time_type]['name'];
		$time_zone = date('Z');
		
		switch($time_type)
		{
			case '24h':
				$now_h = mktime(date('H') + 1,0,0,date('m'),date('d'),date('Y')) - date('Z');
				$filed = "FROM_UNIXTIME(click_time + $time_zone,'%Y%m%d%H') AS gtime,FROM_UNIXTIME(click_time + $time_zone,'%H') AS label";
				$xlabel = "小时";
			break;
	
			case '7d':
				$now_h = mktime(0,0,0,date('m'),date('d') + 1,date('Y')) - date('Z');
				$filed = "FROM_UNIXTIME(click_time + $time_zone,'%Y%m%d') AS gtime,FROM_UNIXTIME(click_time + $time_zone,'%d') AS label";
				$xlabel = "日";
			break;
	
			case '15d':
				$now_h = mktime(0,0,0,date('m'),date('d') + 1,date('Y')) - date('Z');
				$filed = "FROM_UNIXTIME(click_time + $time_zone,'%Y%m%d') AS gtime,FROM_UNIXTIME(click_time + $time_zone,'%d') AS label";
				$xlabel = "日";
			break;
	
			case '1m':
				$now_h = mktime(0,0,0,date('m'),date('d') + 1,date('Y')) - date('Z');
				$filed = "FROM_UNIXTIME(click_time + $time_zone,'%Y%m%d') AS gtime,FROM_UNIXTIME(click_time + $time_zone,'%d') AS label";
				$xlabel = "日";
			break;
	
			case '3m':
				$now_h = mktime(0,0,0,date('m'),date('d') + 1,date('Y')) - date('Z');
				$filed = "FROM_UNIXTIME(click_time + $time_zone,'%Y%m%d') AS gtime,FROM_UNIXTIME(click_time + $time_zone,'%y-%m-%d') AS label";
				$xlabel = "日";
			break;
	
			case '6m':
				$now_h = mktime(0,0,0,date('m'),date('d') + 1,date('Y')) - date('Z');
				$filed = "FROM_UNIXTIME(click_time + $time_zone,'%Y%m%d') AS gtime,FROM_UNIXTIME(click_time + $time_zone,'%y-%m-%d') AS label";
				$xlabel = "日";
			break;
		}
	
		if($time_type == '3m' || $time_type == '6m')
			$xml = '<chart compactDataMode="1" dataSeparator="|" caption="'.$title.'" baseFontSize="11" outCnvBaseFontSize="12" showLabels="1" showColumnShadow="1" animation="1" showAlternateHGridColor="1" AlternateHGridColor="ff5904" divLineColor="ff5904" divLineAlpha="20" alternateHGridAlpha="5" canvasBorderColor="666666" baseFontColor="666666" lineColor="FF5904" lineAlpha="85" showValues="1" rotateValues="1" valuePosition="auto" lineThickness="1" anchorRadius="1" axis="linear" allowPinMode="0" enableIconMouseCursors="0" dynamicAxis="1">';
		else
			$xml = '<chart caption="'.$title.'" xAxisName="'.$xlabel.'" baseFontSize="11" outCnvBaseFontSize="12" yAxisName="'.$ylabel.'" showLabels="1" showColumnShadow="1" animation="1" showAlternateHGridColor="1" AlternateHGridColor="ff5904" divLineColor="ff5904" divLineAlpha="20" alternateHGridAlpha="5" canvasBorderColor="666666" baseFontColor="666666" lineColor="FF5904" lineAlpha="85" showValues="1" rotateValues="1" valuePosition="auto" lineThickness="1" anchorRadius="1">';
	
		$sql = 'SELECT COUNT(ip) AS cnum,'.$filed.' FROM '.DB::table('auction_click_'.$aid)." WHERE click_time < '$now_h' AND click_time > '$old_h' GROUP BY gtime";
		$query = DB::query($sql);
	
		$categories = '';
		$dataset = '';
		$jg = '';
	
		while($data = DB::fetch($query))
		{
			if($time_type == '3m' || $time_type == '6m')
			{
				$categories .= $jg . $data['label'];
				$dataset .= $jg . $data['cnum'];
				$jg = '|';
			}
			else
				$xml.= "\r\n<set label=\"$data[label]\" value=\"$data[cnum]\" />";
		}
	
		if($time_type == '3m' || $time_type == '6m')
		{
			$xml.= "\r\n<categories>$categories</categories>";
			$xml.= "\r\n<dataset>$dataset</dataset>";
		}
	
		$xml.="\r\n</chart>";
	
		echo $xml;
		exit;
    }
	
	private function getTimeTypes($time_type)
	{
		$time_types = array('24h','7d','15d','1m','3m','6m');
		if(empty($time_type) || !in_array($time_type,$time_types))
			$time_type = '24h';
	
		$time_vals = array(
			'6m'=>array(
				'time'=>mktime(0,0,0,date('m') - 6,date('d') + 1,date('Y')) - date('Z'),
				'name'=>'半年数据'
			),
			'3m'=>array(
				'time'=>mktime(0,0,0,date('m') - 3,date('d') + 1,date('Y')) - date('Z'),
				'name'=>'三月数据'
			),
			'1m'=>array(
				'time'=>mktime(0,0,0,date('m') - 1,date('d') + 1,date('Y')) - date('Z'),
				'name'=>'一月数据'
			),
			'15d'=>array(
				'time'=>mktime(0,0,0,date('m'),date('d') - 14,date('Y')) - date('Z'),
				'name'=>'半月数据'
			),
			'7d'=>array(
				'time'=>mktime(0,0,0,date('m'),date('d') - 6,date('Y')) - date('Z'),
				'name'=>'一周数据'
			),
			'24h'=>array(
				'time'=>mktime(date('H') - 23,0,0,date('m'),date('d'),date('Y')) - date('Z'),
				'name'=>'24小时数据'
			)
		);
		
		return array('type'=>$time_type,'vals'=>$time_vals);
	}
	
	public function goods()
	{
		global $_FANWE;
		
		$aid = intval($_FANWE['request']['aid']);
		
		if($aid == 0)
			exit;
		
		$aid = intval(DB::resultFirst('SELECT id FROM '.DB::table('auction').' WHERE user_id = '.$_FANWE['uid'].' AND id = '.$aid));
		
		if($aid == 0)
			exit;
		
		$type = $_FANWE['request']['type'];
		$types = array('edit','update','search');

		if(empty($type) || !in_array($type,$types))
			$type = 'edit';
		
		$site_id = intval(DB::resultFirst('SELECT id FROM '.DB::table('site').' WHERE user_id = '.$_FANWE['uid']));

		if($type == 'search')
		{
			$result = array();
			
			if($site_id > 0)
			{
				$city_id = intval($_FANWE['request']['city_id']);
				if($city_id > 0)
				{
					$keywords = trim($_FANWE['request']['keywords']);
					
					$city_name = DB::resultFirst('SELECT name FROM '.DB::table('group_city')." WHERE id = '$city_id'");
					
					$where = " AND gk.city = '$city_name'";
					
					if($_FANWE['setting']['all_city'] == 1 && $city_name == '全国')
						$where = "";
					
					if($_FANWE['setting']['index_all'] == 1 && $city_name != '全国')
						$where = " AND gk.city IN ('$city_name','全国')";
					
					if(!empty($keywords))
						$where .= " AND g.name LIKE '%$keywords%'";
					
					$query = DB::query("SELECT g.id,g.name,gk.city,(gk.city = '$city_name') AS is_current_city 
									FROM ".DB::table('goods_now_key').' AS gk FORCE INDEX (site_city) 
									INNER JOIN '.DB::table('goods_now').' AS g ON g.id = gk.id 
									WHERE gk.site_id = '.$site_id.$where.' ORDER BY is_current_city DESC,gk.id DESC LIMIT 0,30');
					
					while($data = DB::fetch($query))
					{
						$result[] = $data;
					}
				}
			}
			
			require_once import('class/json');
			$json = new Json();
			die($json->encode($result));
			exit;
		}
		
		if($type == 'update')
		{
			if($site_id > 0)
			{
				$query = DB::query('SELECT gc.id AS city_id,gc.name AS city_name,acg.auction_sort  
								FROM '.DB::table('auction_city_goods').' AS acg 
								LEFT JOIN '.DB::table('group_city').' AS gc ON gc.id = acg.city_id 
								WHERE acg.auction_id = '.$aid);
								
				while($data = DB::fetch($query))
				{
					$goods_id = intval($_FANWE['request']['acg'][$data['city_id']]['goods_id']);
					if($goods_id == 0)
					{
						$city_name = $data['city_name'];
					
						$where = " AND gk.city = '$city_name'";
						
						if($_FANWE['setting']['all_city'] == 1 && $city_name == '全国')
							$where = "";
						
						if($_FANWE['setting']['index_all'] == 1 && $city_name != '全国')
							$where = " AND gk.city IN ('$city_name','全国')";
						
						$goods = DB::fetchFirst("SELECT gk.id,(gk.city = '$city_name') AS is_current_city 
									FROM ".DB::table('goods_now_key').' AS gk FORCE INDEX (site_city) 
									WHERE gk.site_id = '.$site_id.$where.' ORDER BY is_current_city DESC,gk.id DESC LIMIT 0,1');
						
						if($goods)
							$goods_id = intval($goods['id']);
					}
					
					DB::query('REPLACE INTO '.DB::table('auction_city_goods').'(auction_id,site_id,city_id,goods_id,auction_sort) 
									VALUES('.$aid.','.$site_id.','.$data['city_id'].','.$goods_id.','.$data['auction_sort'].')');
				}
				
				clearDir(FANWE_ROOT.'./public/tpl/caches/page_index_index');
			}
		}
		
		$list = array();
		$query = DB::query('SELECT gc.id AS city_id,gc.py_t,gc.name AS city_name,gn.id AS goods_id,gn.name AS goods_name,gn.city AS goods_city 
								FROM '.DB::table('auction_city_goods').' AS acg 
								LEFT JOIN '.DB::table('group_city').' AS gc ON gc.id = acg.city_id 
								LEFT JOIN '.DB::table('goods_now').' AS gn ON gn.id = acg.goods_id 
								WHERE acg.auction_id = '.$aid.' ORDER BY gc.sort ASC,gc.id ASC');
		
		while($data = DB::fetch($query))
		{
			$list[$data['py_t']][] = $data;
		}

		ksort($list);
		include template('site/goods');
		display();
	}
}
?>